//
//  EFAPjtUserAddVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/8/15.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAPjtUserAddVC.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "ApiManager.h"
#import "EFAPjtDetailHView.h"
#import "EFAPjtAddTCell.h"
#import "EFAModel.h"
#import "UIColor+XDHex.h"
#import "GlobalHeader.h"
#import "EFAPjtDetailTCell.h"
#import "EFAPjtUserSelDevVC.h"
#import "EFAPjtDeviceAddVC.h"

@interface EFAPjtUserAddVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource, EFAPjtAddTCellDelegate, EFAPjtDetailHViewDelegate>
@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
//@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (strong, nonatomic) UIBarButtonItem *saveBarBtnItem;
@property (nonatomic, assign)   EFAPjtUserAddVCType viewType;
@property (nonatomic, strong) NSArray<EFAPjtAddViewCfg *> *dataArray;
@property (nonatomic, strong) EFADeviceModel *deviceModel;
@end

static NSString *const kReuseCellId = @"EFAPjtAddTCell";
static NSString *const kReuseDevCellId = @"EFAPjtDetailTCell";
static NSString *const kHeaderViewId = @"EFAPjtDetailHView";

@implementation EFAPjtUserAddVC

#pragma mark - life cycle
- (instancetype)initWithViewType:(EFAPjtUserAddVCType)viewType {
    self = [super init];
    if (self) {
        _viewType = viewType;
        if (viewType != EFAPjtUserAddVCTypeUserEdit && viewType != EFAPjtUserAddVCTypeUserDetail) {
            _userItem = [[EFAPjtDetUserItem alloc] init];
            _deviceModel = [[EFADeviceModel alloc] init];
        }
    }
    return self;
}

- (instancetype)init {
    NSAssert(NO, @"use initWithViewType");
    return nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

//- (BOOL)hidesBottomBarWhenPushed {
//    return self.viewType == EFAPjtManagerVCTypeManager;
//}

- (void)initNavigationBar {
    NSArray<NSString *> *temp = @[@"新增用户", @"给用户分配设备", @"新增管理员", @"用户详情"];
    self.navigationItem.title = temp[self.viewType];
    self.navigationItem.rightBarButtonItem = (self.viewType != EFAPjtUserAddVCTypeUserDetail) ? self.saveBarBtnItem : nil;
    [self.saveBarBtnItem setEnabled:NO];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    UINib *headerNib = [UINib nibWithNibName:kHeaderViewId bundle:nil];
    [self.tableView registerNib:headerNib forHeaderFooterViewReuseIdentifier:kHeaderViewId];
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    UINib *devNib = [UINib nibWithNibName:kReuseDevCellId bundle:nil];
    [self.tableView registerNib:devNib forCellReuseIdentifier:kReuseDevCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
//    self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
//    self.tableView.estimatedSectionHeaderHeight = 60.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //    self.tableView.emptyDataSetDelegate = self;
    //    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    //    self.tableView.mj_header = self.mj_header;
    //    self.tableView.mj_footer = self.mj_footer;
    
    //    [self.tableView.mj_header beginRefreshing];
    if (self.viewType == EFAPjtUserAddVCTypeUserEdit || self.viewType == EFAPjtUserAddVCTypeUserDetail) {
        [self requestUserDeviceListWithHeader:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//#pragma mark - DZNEmptyDataSetSource
//- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
//    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
//    return [[NSAttributedString alloc] initWithString:@"当前没有项目" attributes:dic];
//}
//
//- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
//    //    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
//    return nil;
//}
//
////- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
////    return -100.0;
////}
//#pragma mark - DZNEmptyDataSetDelegate
//- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
//    return YES;
//}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return (self.viewType == EFAPjtUserAddVCTypeGMAdd) ? 1 : 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.dataArray.count;
    } else if (section == 1) {
        return self.deviceModel.device_list.count;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        EFAPjtAddTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
        if (indexPath.row < self.dataArray.count) {
            [cell configViewWithViewCfg:self.dataArray[indexPath.row]];
        }
        cell.delegate = self;
        return cell;
    }
    EFAPjtDetailTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseDevCellId forIndexPath:indexPath];
    if (indexPath.row < self.deviceModel.device_list.count) {
        [cell configViewWithDeviceListItem:self.deviceModel.device_list[indexPath.row]];
    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return (section == 0) ? 0.1 : 59;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        EFAPjtDetailHView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kHeaderViewId];
        NSString *title = [NSString stringWithFormat:@"该用户管理的设备(%ld)", (unsigned long)self.deviceModel.device_list.count];
        view.titleLabel.text = title;
        view.btnTitle = @"分配设备";
        view.managerBtn.hidden = (self.viewType == EFAPjtUserAddVCTypeUserDetail);
        view.section = section;
        view.delegate = self;
        return view;
    }
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 1 && indexPath.row < self.deviceModel.device_list.count) {
        [self jumpToDeviceDetailWithDevItem:self.deviceModel.device_list[indexPath.row]];
    }
}

#pragma mark - EFAPjtAddTCellDelegate
- (void)pjtAddTCell:(EFAPjtAddTCell *)cell editChanged:(UITextField *)textField {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath.section == 0) {
        if (indexPath.row < self.dataArray.count) {
            EFAPjtAddViewCfg *cfg = self.dataArray[indexPath.row];
            cfg.value = textField.text;
        }
    }
    self.saveBarBtnItem.enabled = [self checkSaveBtnState];
}

#pragma mark - EFAPjtDetailHViewDelegate
- (void)pjtDetailHView:(EFAPjtDetailHView *)view section:(NSInteger)section managerBtnTapped:(UIButton *)btn {
    if (section == 1) {
        [self jumpToSelDevice];
    }
}

#pragma mark - event response
- (void)addBarBtnTapped:(UIBarButtonItem *)item {
    if (![self checkUserInput]) {
        return;
    }
    
    //请求服务器
    if (self.viewType == EFAPjtUserAddVCTypeUserAdd) {
        [self requestAddUser];
    } else if(self.viewType == EFAPjtUserAddVCTypeUserEdit) {
        [self requestEditUser];
    } else if (self.viewType == EFAPjtUserAddVCTypeGMAdd) {
        [self requestAddGM];
    }
}
#pragma mark - private methods
- (void)jumpToDeviceDetailWithDevItem:(EFADeviceListItem *)item {
    EFAPjtDeviceAddVC *vc = [[EFAPjtDeviceAddVC alloc] initWithViewType:EFAPjtDeviceAddVCTypeDetail];
    vc.project_id = self.project_id;
    vc.deviceItem = item;
    [self showViewController:vc sender:nil];
}
- (void)jumpToSelDevice {
    EFAPjtUserSelDevVC *vc = [[EFAPjtUserSelDevVC alloc] init];
    vc.project_id = self.project_id;
    vc.pjtUser_id = self.userItem.efairyuser_id;
    vc.successHandle = ^(NSArray<EFADeviceListItem *> *selArray) {
        if (selArray) {
            self.deviceModel = [[EFADeviceModel alloc] initWithListArray:selArray];
        }
        [self refreshWholeView];
    };
    [self showViewController:vc sender:nil];
}
- (BOOL)checkUserInput {
    for (EFAPjtAddViewCfg *cfg in self.dataArray) {
        if (cfg.value.length < cfg.valueMinLen || cfg.value.length > cfg.valueMaxLen) {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:cfg.prompt];
            return NO;
        }
    }
    return YES;
}

- (BOOL)checkSaveBtnState {
    for (EFAPjtAddViewCfg *cfg in self.dataArray) {
        if (!cfg.value.length) {
            return NO;
        }
    }
    return YES;
}

- (NSMutableDictionary *)parametersDictionary {
    NSMutableDictionary *mDic = [[NSMutableDictionary alloc] init];
    for (EFAPjtAddViewCfg *cfg in self.dataArray) {
        [mDic setObject:cfg.value forKey:cfg.key];
        // Key-Value来更改原始值
        [self.userItem setValue:cfg.value forKey:cfg.key];
    }
    // 没有的参数也加进来，比如坐标
    [mDic setObject:@(self.project_id) forKey:@"efairyproject_id"];
    return mDic;
}

- (void)refreshWholeView {
    //    // 尾部加载更多的显示
    //    if (self.userList.totalLoad) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    self.saveBarBtnItem.enabled = [self checkSaveBtnState];
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
//    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    //    [self requestUserListWithHeader:isHeader];
}

- (void)backToParent {
    if (self.successHandle) {
        self.successHandle();
        self.successHandle = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - network request
- (void)requestAddUser {
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSMutableDictionary *pars = [self parametersDictionary];
    [pars setObject:self.deviceModel.idListArray forKey:@"efairydevice_id_list"];
    [pars setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [pars setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
    NSLog(@"添加用户的参数 = %@", pars);
    
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiPjtMgrUserDevice] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"添加用户返回：%@", responseObject);
        [hud hideAnimated:NO];
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"添加用户成功"];
        temp.completionBlock = ^{
            [self backToParent];
        };
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"添加用户失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

- (void)requestEditUser {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSMutableDictionary *pars = [self parametersDictionary];
    [pars setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [pars setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
    [pars setObject:@(self.userItem.efairyuser_id) forKey:@"efairyproject_user_id"];
    [pars setObject:[self.deviceModel idListArray] forKey:@"efairydevice_id_list"];
    NSLog(@"编辑设备的参数 = %@", pars);
    
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiPjtMgrUserAddDev] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"编辑用户返回：%@", responseObject);
        [hud hideAnimated:NO];
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"编辑用户成功"];
        temp.completionBlock = ^{
            [self backToParent];
        };
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"编辑用户失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

- (void)requestAddGM {
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSMutableDictionary *pars = [self parametersDictionary];
    [pars setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [pars setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
    NSLog(@"添加管理员的参数 = %@", pars);
    
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiPjtMgrGM] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"添加管理员返回：%@", responseObject);
        [hud hideAnimated:NO];
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"添加管理员成功"];
        temp.completionBlock = ^{
            [self backToParent];
        };
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"添加管理员失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

- (void)requestUserDeviceListWithHeader:(BOOL)isHeader {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
//        [self tableViewEndRefresh:isHeader];
        return;
    }
    
    NSInteger last_id = isHeader ? 0 : self.deviceModel.device_list.lastObject.efairydevice_id;
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairyproject_id" : @(self.project_id),
                           @"efairyproject_user_id" : @(self.userItem.efairyuser_id),
                           @"last_id" : @(last_id),
                           @"size" : @(NSIntegerMax)};
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiPjtMgrUserDevList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求设备列表返回：%@", responseObject);
        [hud hideAnimated:YES];
        self.deviceModel = [EFADeviceModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求设备列表失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UIBarButtonItem *)saveBarBtnItem {
    if (!_saveBarBtnItem) {
        _saveBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(addBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_saveBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_saveBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _saveBarBtnItem;
}

- (NSArray<EFAPjtAddViewCfg *> *)dataArray {
    if (!_dataArray) {
        EFAPjtAddViewCfg *cfg1 = ({
            EFAPjtAddViewCfg * cfg = [[EFAPjtAddViewCfg alloc] init];
            cfg.key = @"efairyuser_nickname";
            cfg.keyDes = @"姓名";
            cfg.value = self.userItem.efairyuser_nickname;
            cfg.keyboardType = UIKeyboardTypeDefault;
            cfg.isInput = YES;
            cfg.isTextField = YES;
            cfg.valueMinLen = 1;
            cfg.valueMaxLen = 15;
            cfg.prompt = @"名字的长度为1-15个字符";
            cfg.enabled = (self.viewType != EFAPjtUserAddVCTypeUserEdit  && self.viewType != EFAPjtUserAddVCTypeUserDetail);
            cfg;
        });
        
        EFAPjtAddViewCfg *cfg2 = ({
            EFAPjtAddViewCfg * cfg = [[EFAPjtAddViewCfg alloc] init];
            cfg.key = @"efairyuser_phonenumber";
            cfg.keyDes = @"手机号";
            cfg.value = self.userItem.efairyuser_phonenumber;
            cfg.keyboardType = UIKeyboardTypeNumberPad;
            cfg.isInput = YES;
            cfg.isTextField = YES;
            cfg.valueMinLen = 11;
            cfg.valueMaxLen = 11;
            cfg.prompt = @"请输入11位手机号";
            cfg.enabled = (self.viewType != EFAPjtUserAddVCTypeUserEdit && self.viewType != EFAPjtUserAddVCTypeUserDetail);
            cfg;
        });
        
        _dataArray = @[cfg1, cfg2];
    }
    return _dataArray;
}

- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

@end
